/**
 * @date: 2025/3/20
 * @author: 小红
 * @Description: 请求
 */

import { type _ApiDataList, type _AxiosRequestConfig, APPLICATION_JSON, REQUEST_TIMEOUT } from '@/utils/http/types';
import { useEnv } from '@/hooks/useEnv';
import { createError, createRequestInterceptors, createResponseInterceptors } from '@/utils/http/helper.ts';
import axios from 'axios';

const AxiosInstance = axios.create({
	baseURL: useEnv('VITE_API_URL'),
	timeout: REQUEST_TIMEOUT,
	withCredentials: false, // 禁用 Cookie 等信息
	headers: {
		'Content-Type': APPLICATION_JSON,
	},
});

/**
 * 请求
 */
AxiosInstance.interceptors.request.use(createRequestInterceptors, createError);
/**
 * 响应
 */
AxiosInstance.interceptors.response.use(createResponseInterceptors, createError);

const http = {
	get<T = any, D extends boolean = false>(url: string, params?: any, config?: _AxiosRequestConfig): Promise<D extends true ? _ApiDataList<T> : T> {
		return AxiosInstance({ method: 'get', url, params, ...config });
	},
	post<T = any, D extends boolean = false>(url: string, data?: any, config?: _AxiosRequestConfig): Promise<D extends true ? _ApiDataList<T> : T> {
		return AxiosInstance({ method: 'post', url, data, ...config });
	},
	put<T = any, D extends boolean = false>(url: string, data?: any, config?: _AxiosRequestConfig): Promise<D extends true ? _ApiDataList<T> : T> {
		return AxiosInstance({ method: 'put', url, data, ...config });
	},
	delete<T = any, D extends boolean = false>(url: string, data?: any, config?: _AxiosRequestConfig): Promise<D extends true ? _ApiDataList<T> : T> {
		return AxiosInstance({ method: 'delete', url, data, ...config });
	},
};

export default http;
